package com.agnes.network.security;

import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

/**
 * Desc:
 * Creator ling
 * Date:   2017/5/15 0015 18:00
 */

public class SSLUtils {

    /**
     * 获取Https的证书,手动导入证书过期得更换
     *
     * @param certificates 证书的输入流  getAssets().open("ca.cer")
     * @return
     */
    public static SSLSocketFactory getSocketFactory(InputStream... certificates) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            //创建一个证书库，并将证书导入证书库
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null); //双向验证时使用
            int index = 0;
            for (InputStream inputStream : certificates) {
                String alias = Integer.toString(index++);
                Certificate cer = certificateFactory.generateCertificate(inputStream);
                keystore.setCertificateEntry(alias, cer);
                try {
                    if (inputStream != null) inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 实例化信任库
            TrustManagerFactory trustManagerFactory =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            // 初始化信任库
            trustManagerFactory.init(keystore);
            return createSSLSocketFactory(trustManagerFactory.getTrustManagers());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 信任所有证书 （官方不推荐使用）
     *
     * @return
     */
    public static SSLSocketFactory getDefaultSocketFactory() {
        TrustManager[] trustManagers = new TrustManager[] {
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }
        };

        return createSSLSocketFactory(trustManagers);
    }

    private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustManagers) {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
